(function () {
  function parseDate(attr) {
    if (!attr) {
      var d = new Date();
      return { y: d.getFullYear(), m: d.getMonth() + 1, d: d.getDate() };
    }
    var m = attr.match(/^(\d{4})-(\d{2})-(\d{2})$/);
    if (m) return { y: parseInt(m[1], 10), m: parseInt(m[2], 10), d: parseInt(m[3], 10) };
    var d2 = new Date(attr);
    if (!isNaN(d2)) return { y: d2.getFullYear(), m: d2.getMonth() + 1, d: d2.getDate() };
    var now = new Date();
    return { y: now.getFullYear(), m: now.getMonth() + 1, d: now.getDate() };
  }

  function toArray(val) {
    if (!val) return [];
    if (Array.isArray(val)) return val;
    if (typeof val === 'string') return val.split(/[ ,，、]+/).filter(Boolean);
    try {
      return Array.from(val);
    } catch (e) {
      return [];
    }
  }

  function fillList(ul, arr) {
    if (!ul) return;
    ul.innerHTML = '';
    if (!arr || arr.length === 0) {
      var li = document.createElement('li');
      li.textContent = '暂无数据';
      ul.appendChild(li);
      return;
    }
    arr.slice(0, 12).forEach(function (txt) {
      var li = document.createElement('li');
      li.textContent = txt;
      ul.appendChild(li);
    });
  }

  function render(container) {
    var dateObj = parseDate(container.getAttribute('data-date'));
    if (!window.Solar) {
      console.error('lunar-javascript 未加载或不可用');
      return;
    }
    var solar = Solar.fromYmd(dateObj.y, dateObj.m, dateObj.d);
    var lunar = solar.getLunar();

    var dateEl = container.querySelector('.scf-almanac-date');
    var lunarEl = container.querySelector('.scf-almanac-lunar');
    var yiUl = container.querySelector('.scf-almanac-yis');
    var jiUl = container.querySelector('.scf-almanac-jis');

    if (dateEl) dateEl.textContent = solar.toString() + ' ' + solar.getWeek();
    if (lunarEl) lunarEl.textContent = lunar.toString();

    // 兼容不同版本的API命名：优先日宜/日忌，次选通用宜/忌
    var yis = (typeof lunar.getDayYi === 'function') ? lunar.getDayYi()
              : (typeof lunar.getYi === 'function') ? lunar.getYi()
              : null;
    var jis = (typeof lunar.getDayJi === 'function') ? lunar.getDayJi()
              : (typeof lunar.getJi === 'function') ? lunar.getJi()
              : null;

    fillList(yiUl, toArray(yis));
    fillList(jiUl, toArray(jis));
  }

  function init() {
    document.querySelectorAll('.scf-almanac').forEach(render);
  }
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();